<template>
  <div class="role-manage">
    <el-card class="page-card">
      <template #header>
        <div class="card-header">
          <span class="title">角色权限管理</span>
        </div>
      </template>
      
      <el-row :gutter="24">
        <!-- 角色列表 -->
        <el-col :span="8">
          <el-card class="role-card">
            <template #header>
              <span class="card-title">角色列表</span>
            </template>
            
            <div class="role-list">
              <div
                v-for="role in roleList"
                :key="role.code"
                class="role-item"
                :class="{ active: selectedRole === role.code }"
                @click="selectRole(role.code)"
              >
                <div class="role-info">
                  <div class="role-name">{{ role.name }}</div>
                  <div class="role-desc">{{ role.description }}</div>
                  <div class="permission-count">
                    权限数量: {{ getRolePermissionCount(role.code) }}
                  </div>
                </div>
                <el-icon class="role-arrow">
                  <ArrowRight />
                </el-icon>
              </div>
            </div>
          </el-card>
        </el-col>
        
        <!-- 权限配置 -->
        <el-col :span="16">
          <el-card class="permission-card" v-if="selectedRole">
            <template #header>
              <div class="permission-header">
                <span class="card-title">
                  {{ getRoleName(selectedRole) }} - 权限配置
                </span>
                <el-button type="primary" @click="savePermissions" :loading="saving">
                  保存权限
                </el-button>
              </div>
            </template>
            
            <div v-loading="permissionLoading" class="permission-content">
              <div
                v-for="module in permissionModules"
                :key="module"
                class="permission-module"
              >
                <div class="module-header">
                  <el-checkbox
                    :model-value="isModuleAllSelected(module)"
                    :indeterminate="isModuleIndeterminate(module)"
                    @change="toggleModulePermissions(module, $event)"
                  >
                    {{ getModuleName(module) }}
                  </el-checkbox>
                </div>
                
                <div class="module-permissions">
                  <el-checkbox-group v-model="selectedPermissions">
                    <el-row :gutter="16">
                      <el-col
                        :span="12"
                        v-for="permission in getModulePermissions(module)"
                        :key="permission.id"
                      >
                        <el-checkbox
                          :label="permission.id"
                          class="permission-checkbox"
                        >
                          <div class="permission-info">
                            <div class="permission-name">{{ permission.name }}</div>
                            <div class="permission-desc">{{ permission.description }}</div>
                          </div>
                        </el-checkbox>
                      </el-col>
                    </el-row>
                  </el-checkbox-group>
                </div>
              </div>
            </div>
          </el-card>
          
          <el-card v-else class="empty-card">
            <el-empty description="请选择一个角色来配置权限" />
          </el-card>
        </el-col>
      </el-row>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { rolePermissionApi, permissionApi } from '@/api/system'

// 响应式数据
const permissionLoading = ref(false)
const saving = ref(false)
const selectedRole = ref('')
const selectedPermissions = ref<number[]>([])
const allPermissions = ref<any[]>([])
const rolePermissions = ref<Record<string, any>>({})

// 角色列表
const roleList = reactive([
  {
    code: 'admin',
    name: '管理员',
    description: '系统管理员，拥有所有权限'
  },
  {
    code: 'teacher',
    name: '老师',
    description: '教师用户，可以管理学生和面试'
  },
  {
    code: 'student',
    name: '学生',
    description: '学生用户，可以制作简历和参加面试'
  }
])

// 计算属性
const permissionModules = computed(() => {
  const modules = new Set()
  if (Array.isArray(allPermissions.value)) {
    allPermissions.value.forEach((permission: any) => {
      modules.add(permission.module)
    })
  }
  return Array.from(modules)
})

// 方法
const fetchPermissions = async () => {
  permissionLoading.value = true
  try {
    // 获取所有权限，不分页
    const response = await permissionApi.getPermissionList({ page_size: 1000 })
    console.log('权限API响应:', response)

    // 确保返回的是数组
    if (response.data && response.data.results && Array.isArray(response.data.results)) {
      allPermissions.value = response.data.results
    } else if (response.data && Array.isArray(response.data)) {
      allPermissions.value = response.data
    } else if (Array.isArray(response)) {
      allPermissions.value = response
    } else {
      allPermissions.value = []
      console.warn('权限API返回的数据格式不正确:', response)
    }

    console.log('处理后的权限数据:', allPermissions.value)
  } catch (error) {
    console.error('获取权限列表失败:', error)
    ElMessage.error('获取权限列表失败')
    allPermissions.value = []
  } finally {
    permissionLoading.value = false
  }
}

const fetchRolePermissions = async () => {
  try {
    const response = await rolePermissionApi.getRolePermissions()
    console.log('角色权限API原始响应:', response)

    // 处理不同的响应格式
    let rolePermissionsData = {}
    if (response.data) {
      rolePermissionsData = response.data
    } else if (response) {
      rolePermissionsData = response
    }

    rolePermissions.value = rolePermissionsData
    console.log('处理后的角色权限数据:', rolePermissions.value)

    // 如果没有数据，创建默认的空权限结构
    if (Object.keys(rolePermissions.value).length === 0) {
      rolePermissions.value = {
        admin: [],
        teacher: [],
        student: []
      }
      console.log('使用默认权限结构')
    }
  } catch (error) {
    console.error('获取角色权限失败:', error)
    ElMessage.error('获取角色权限失败')
    // 设置默认的空权限结构
    rolePermissions.value = {
      admin: [],
      teacher: [],
      student: []
    }
  }
}

const selectRole = (roleCode: string) => {
  console.log('选择角色:', roleCode)
  console.log('角色权限数据:', rolePermissions.value)
  console.log('当前角色权限:', rolePermissions.value[roleCode])

  selectedRole.value = roleCode
  const roleData = rolePermissions.value[roleCode]

  if (roleData) {
    // 处理不同的数据结构
    if (Array.isArray(roleData)) {
      // 如果roleData直接是权限ID数组
      selectedPermissions.value = roleData
    } else if (roleData.permissions) {
      // 如果roleData是对象，包含permissions字段
      if (Array.isArray(roleData.permissions)) {
        // 如果permissions是对象数组
        if (roleData.permissions.length > 0 && typeof roleData.permissions[0] === 'object') {
          selectedPermissions.value = roleData.permissions.map((p: any) => p.id || p.permission_id)
        } else {
          // 如果permissions是ID数组
          selectedPermissions.value = roleData.permissions
        }
      } else {
        selectedPermissions.value = []
      }
    } else {
      selectedPermissions.value = []
    }
    console.log('选中的权限ID:', selectedPermissions.value)
  } else {
    selectedPermissions.value = []
    console.warn('未找到角色权限数据:', roleCode)
  }
}

const getRoleName = (roleCode: string) => {
  const role = roleList.find(r => r.code === roleCode)
  return role?.name || roleCode
}

const getRolePermissionCount = (roleCode: string) => {
  const roleData = rolePermissions.value[roleCode]
  if (!roleData) return 0

  if (Array.isArray(roleData)) {
    return roleData.length
  } else if (roleData.permissions) {
    return Array.isArray(roleData.permissions) ? roleData.permissions.length : 0
  }
  return 0
}

const getModuleName = (module: string) => {
  const moduleNames: Record<string, string> = {
    'user': '用户管理',
    'student': '学生管理',
    'resume': '简历管理',
    'interview': '面试管理',
    'job': '岗位管理',
    'notification': '通知管理',
    'file': '文件管理',
    'system': '系统管理',
    'audit': '审计日志'
  }
  return moduleNames[module] || module
}

const getModulePermissions = (module: string) => {
  if (!Array.isArray(allPermissions.value)) {
    return []
  }
  return allPermissions.value.filter((permission: any) => permission.module === module)
}

const isModuleAllSelected = (module: string) => {
  const modulePermissions = getModulePermissions(module)
  return modulePermissions.length > 0 && 
         modulePermissions.every((permission: any) => selectedPermissions.value.includes(permission.id))
}

const isModuleIndeterminate = (module: string) => {
  const modulePermissions = getModulePermissions(module)
  const selectedCount = modulePermissions.filter((permission: any) => 
    selectedPermissions.value.includes(permission.id)
  ).length
  return selectedCount > 0 && selectedCount < modulePermissions.length
}

const toggleModulePermissions = (module: string, checked: boolean | string | number) => {
  const isChecked = Boolean(checked)
  const modulePermissions = getModulePermissions(module)
  const modulePermissionIds = modulePermissions.map((permission: any) => permission.id)

  if (isChecked) {
    // 添加模块所有权限
    modulePermissionIds.forEach(id => {
      if (!selectedPermissions.value.includes(id)) {
        selectedPermissions.value.push(id)
      }
    })
  } else {
    // 移除模块所有权限
    selectedPermissions.value = selectedPermissions.value.filter(
      id => !modulePermissionIds.includes(id)
    )
  }
}

const savePermissions = async () => {
  if (!selectedRole.value) {
    ElMessage.warning('请选择角色')
    return
  }
  
  saving.value = true
  try {
    await rolePermissionApi.updateRolePermissions({
      role: selectedRole.value,
      permission_ids: selectedPermissions.value
    })
    
    ElMessage.success('权限保存成功')
    await fetchRolePermissions()
  } catch (error) {
    ElMessage.error('权限保存失败')
  } finally {
    saving.value = false
  }
}

// 创建模拟权限数据（用于测试）
const createMockPermissions = () => {
  const mockPermissions = [
    // 用户管理模块
    { id: 1, name: '查看用户', description: '查看用户列表和详情', module: 'user', codename: 'view_user' },
    { id: 2, name: '添加用户', description: '创建新用户', module: 'user', codename: 'add_user' },
    { id: 3, name: '编辑用户', description: '修改用户信息', module: 'user', codename: 'change_user' },
    { id: 4, name: '删除用户', description: '删除用户账号', module: 'user', codename: 'delete_user' },

    // 学生管理模块
    { id: 5, name: '查看学生', description: '查看学生列表和详情', module: 'student', codename: 'view_student' },
    { id: 6, name: '添加学生', description: '创建新学生', module: 'student', codename: 'add_student' },
    { id: 7, name: '编辑学生', description: '修改学生信息', module: 'student', codename: 'change_student' },
    { id: 8, name: '删除学生', description: '删除学生记录', module: 'student', codename: 'delete_student' },

    // 简历管理模块
    { id: 9, name: '查看简历', description: '查看简历列表和详情', module: 'resume', codename: 'view_resume' },
    { id: 10, name: '审核简历', description: '审核学生简历', module: 'resume', codename: 'review_resume' },
    { id: 11, name: '编辑简历', description: '修改简历内容', module: 'resume', codename: 'change_resume' },
    { id: 12, name: '删除简历', description: '删除简历记录', module: 'resume', codename: 'delete_resume' },

    // 面试管理模块
    { id: 13, name: '查看面试', description: '查看面试安排和记录', module: 'interview', codename: 'view_interview' },
    { id: 14, name: '安排面试', description: '创建面试安排', module: 'interview', codename: 'add_interview' },
    { id: 15, name: '修改面试', description: '修改面试安排', module: 'interview', codename: 'change_interview' },
    { id: 16, name: '取消面试', description: '取消面试安排', module: 'interview', codename: 'delete_interview' },

    // 岗位管理模块
    { id: 17, name: '查看岗位', description: '查看岗位列表和详情', module: 'job', codename: 'view_job' },
    { id: 18, name: '发布岗位', description: '发布新岗位', module: 'job', codename: 'add_job' },
    { id: 19, name: '编辑岗位', description: '修改岗位信息', module: 'job', codename: 'change_job' },
    { id: 20, name: '删除岗位', description: '删除岗位记录', module: 'job', codename: 'delete_job' },

    // 系统管理模块
    { id: 21, name: '系统设置', description: '修改系统配置', module: 'system', codename: 'change_settings' },
    { id: 22, name: '查看日志', description: '查看系统日志', module: 'system', codename: 'view_logs' },
    { id: 23, name: '用户权限', description: '管理用户权限', module: 'system', codename: 'manage_permissions' },
    { id: 24, name: '数据备份', description: '备份系统数据', module: 'system', codename: 'backup_data' }
  ]

  return mockPermissions
}

// 创建模拟角色权限数据
const createMockRolePermissions = () => {
  return {
    admin: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24], // 管理员拥有所有权限
    teacher: [5, 6, 7, 9, 10, 11, 13, 14, 15, 16, 17, 18, 19], // 教师权限
    student: [5, 9, 11, 13, 17] // 学生权限
  }
}

// 生命周期
onMounted(async () => {
  console.log('RoleManage组件挂载，开始获取数据...')
  await fetchPermissions()
  await fetchRolePermissions()

  // 如果没有权限数据，使用模拟数据
  if (allPermissions.value.length === 0) {
    console.log('使用模拟权限数据')
    allPermissions.value = createMockPermissions()
  }

  // 如果没有角色权限数据，使用模拟数据
  if (Object.keys(rolePermissions.value).length === 0 ||
      Object.values(rolePermissions.value).every(perms => Array.isArray(perms) && perms.length === 0)) {
    console.log('使用模拟角色权限数据')
    rolePermissions.value = createMockRolePermissions()
  }

  console.log('数据获取完成')
  console.log('权限模块:', permissionModules.value)
  console.log('最终权限数据:', allPermissions.value)
  console.log('最终角色权限数据:', rolePermissions.value)
})
</script>

<style lang="scss" scoped>
.role-manage {
  .page-card {
    .card-header {
      .title {
        font-size: 18px;
        font-weight: 600;
        color: var(--text-color-primary);
      }
    }
  }
  
  .role-card {
    height: 600px;
    
    .card-title {
      font-weight: 600;
      color: var(--text-color-primary);
    }
    
    .role-list {
      .role-item {
        display: flex;
        align-items: center;
        justify-content: space-between;
        padding: 16px;
        margin-bottom: 8px;
        border: 1px solid var(--border-color-lighter);
        border-radius: 8px;
        cursor: pointer;
        transition: all 0.3s ease;
        
        &:hover {
          border-color: var(--color-primary);
          background-color: var(--fill-color-light);
        }
        
        &.active {
          border-color: var(--color-primary);
          background-color: var(--color-primary-light-9);
        }
        
        .role-info {
          flex: 1;
          
          .role-name {
            font-size: 16px;
            font-weight: 600;
            color: var(--text-color-primary);
            margin-bottom: 4px;
          }
          
          .role-desc {
            font-size: 12px;
            color: var(--text-color-secondary);
            margin-bottom: 4px;
          }
          
          .permission-count {
            font-size: 12px;
            color: var(--color-primary);
          }
        }
        
        .role-arrow {
          color: var(--text-color-placeholder);
        }
      }
    }
  }
  
  .permission-card {
    height: 600px;
    
    .permission-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      
      .card-title {
        font-weight: 600;
        color: var(--text-color-primary);
      }
    }
    
    .permission-content {
      height: 500px;
      overflow-y: auto;
      
      .permission-module {
        margin-bottom: 24px;
        
        .module-header {
          padding: 12px 0;
          border-bottom: 1px solid var(--border-color-lighter);
          margin-bottom: 16px;
          
          .el-checkbox {
            font-weight: 600;
            font-size: 16px;
          }
        }
        
        .module-permissions {
          padding-left: 24px;
          
          .permission-checkbox {
            width: 100%;
            margin-bottom: 12px;
            
            .permission-info {
              .permission-name {
                font-size: 14px;
                color: var(--text-color-primary);
                margin-bottom: 2px;
              }
              
              .permission-desc {
                font-size: 12px;
                color: var(--text-color-secondary);
              }
            }
          }
        }
      }
    }
  }
  
  .empty-card {
    height: 600px;
    display: flex;
    align-items: center;
    justify-content: center;
  }
}
</style>
